package cn.zhentao.controller;

import cn.zhentao.config.DashScopeConfig;
import cn.zhentao.util.OptimizedAiCaller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("XinAi")
@CrossOrigin(origins = {
    "http://localhost:3000",
    "http://localhost:5173", 
    "http://localhost:8080",
    "http://127.0.0.1:3000",
    "http://127.0.0.1:5173",
    "http://127.0.0.1:8080"
}, allowCredentials = "true")
public class AiController {
    
    private static final Logger logger = LoggerFactory.getLogger(AiController.class);
    
    @Autowired
    private DashScopeConfig dashScopeConfig;
    
    @Autowired
    private OptimizedAiCaller optimizedAiCaller;
    
    // 获取配置的getter方法
    private String getApiKey() {
        return dashScopeConfig.getApiKey();
    }
    
    private String getAppId() {
        return dashScopeConfig.getAppId();
    }
    

    @PostMapping("/chat")
    public Map<String, Object> chatWithAI(@RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        
        logger.info("收到AI聊天请求: {}", request);
        
        try {
            String userMessage = request.get("message");
            if (userMessage == null || userMessage.trim().isEmpty()) {
                logger.warn("用户消息为空");
                response.put("success", false);
                response.put("message", "消息不能为空");
                return response;
            }
            
            // 检查配置
            logger.info("检查AI配置 - API Key: {}, App ID: {}", 
                getApiKey() != null && !getApiKey().trim().isEmpty() ? "已配置" : "未配置",
                getAppId() != null && !getAppId().trim().isEmpty() ? "已配置" : "未配置");
            
            if (getApiKey() == null || getApiKey().trim().isEmpty()) {
                logger.error("API Key未配置");
                response.put("success", false);
                response.put("message", "API Key未配置，请在配置文件中设置dashscope.api.key");
                return response;
            }
            
            if (getAppId() == null || getAppId().trim().isEmpty()) {
                logger.error("应用ID未配置");
                response.put("success", false);
                response.put("message", "应用ID未配置，请在配置文件中设置dashscope.app.id");
                return response;
            }
            
            // 调用AI接口（带超时控制和重试机制）
            logger.info("开始调用AI，用户消息: {}", userMessage);
            OptimizedAiCaller.AiCallResult aiResult = optimizedAiCaller.callWithRetry(userMessage, 2);
            
            if (aiResult.isSuccess() && aiResult.getResponse() != null && !aiResult.getResponse().trim().isEmpty()) {
                response.put("success", true);
                response.put("message", "对话成功");
                response.put("userMessage", userMessage);
                response.put("aiResponse", aiResult.getResponse());
                response.put("duration", aiResult.getDuration());
                logger.info("AI对话成功，耗时: {}ms, AI回复: {}", aiResult.getDuration(), aiResult.getResponse());
            } else {
                response.put("success", false);
                response.put("message", "AI对话失败: " + (aiResult.getErrorMessage() != null ? aiResult.getErrorMessage() : "AI未返回有效内容"));
                response.put("duration", aiResult.getDuration());
                response.put("userMessage", userMessage);
                logger.error("AI对话失败，耗时: {}ms, 错误: {}", aiResult.getDuration(), aiResult.getErrorMessage());
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "AI对话失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }
    
    /**
     * 获取AI对话配置状态
     */
    @GetMapping("/config/status")
    public Map<String, Object> getConfigStatus() {
        Map<String, Object> status = new HashMap<>();
        status.put("apiKeyConfigured", getApiKey() != null && !getApiKey().trim().isEmpty());
        status.put("appIdConfigured", getAppId() != null && !getAppId().trim().isEmpty());
        status.put("fullyConfigured", 
            (getApiKey() != null && !getApiKey().trim().isEmpty()) && 
            (getAppId() != null && !getAppId().trim().isEmpty()));
        return status;
    }
    
    /**
     * 测试AI连接
     */
    @GetMapping("/test")
    public Map<String, Object> testAIConnection() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            if (getApiKey() == null || getApiKey().trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "API Key未配置");
                return response;
            }
            
            if (getAppId() == null || getAppId().trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "应用ID未配置");
                return response;
            }
            
            // 发送测试消息（带超时控制）
            OptimizedAiCaller.AiCallResult testResult = optimizedAiCaller.callWithTimeout("你好，请简单介绍一下你自己");
            
            if (testResult.isSuccess()) {
                response.put("success", true);
                response.put("message", "AI连接测试成功");
                response.put("testResponse", testResult.getResponse());
                response.put("duration", testResult.getDuration());
                logger.info("AI测试成功，耗时: {}ms", testResult.getDuration());
            } else {
                response.put("success", false);
                response.put("message", "AI连接测试失败: " + testResult.getErrorMessage());
                response.put("duration", testResult.getDuration());
                logger.error("AI测试失败，耗时: {}ms, 错误: {}", testResult.getDuration(), testResult.getErrorMessage());
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "AI连接测试失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }
    

    
    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public Map<String, Object> health() {
        Map<String, Object> health = new HashMap<>();
        health.put("status", "UP");
        health.put("service", "AI Tutor Service");
        health.put("timestamp", System.currentTimeMillis());
        health.put("port", "8083");
        health.put("endpoint", "/XinAi/chat");
        return health;
    }
    
    /**
     * 简单的测试接口
     */
    @GetMapping("/test-simple")
    public Map<String, Object> testSimple() {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "AI服务连接正常");
        response.put("timestamp", System.currentTimeMillis());
        response.put("apiKeyConfigured", getApiKey() != null && !getApiKey().trim().isEmpty());
        response.put("appIdConfigured", getAppId() != null && !getAppId().trim().isEmpty());
        return response;
    }
}
